<?php

require_once 'phpmoko/ui/Widget.php';

class Template extends Widget
{
	private $tpl_file;
	private $vars = array();
	private $template_content;

	function Template($template_file)
	{
		parent::__construct();

		$this->tpl_file = $template_file;
		
		$this->template_content = file_get_contents($this->tpl_file);
		if ($this->template_content === false)
			die("Template not founded: ".$this->tpl_file);
	}

	/**
	 * @param $key
	 * @param Widget $widget
	 */
	function setWidget($key, $widget)
	{
		$this->vars[$key] = $widget;
	}

	function toStringParse()
	{
		foreach ($this->vars as $key => $val)
		{
			if ($val instanceof Widget)
				$$key = $val->toString();
			else
				$$key = $val;
		}

		$content = str_replace("'", "\\'", $this->template_content);
		$content = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "'.$\\1.'", $content);
		eval("\$content = '$content';");
		return str_replace("\\'", "'", $content);
	}
	
	function toStringEval()
	{
		foreach ($this->vars as $key => $val)
		{
			if ($val instanceof Widget)
				$$key = $val->toString();
			else
				$$key = $val;
		}
		
		ob_start();
		print eval('?>'.$this->template_content);
		$output = ob_get_contents();
		ob_end_clean();
		
		return $output;
	}

	function toString()
	{
		if (stripos($this->tpl_file, '.phtml') === false)
			return $this->toStringParse();
			
		return $this->toStringEval();
	}
}
?>